package controller;

import java.rmi.RemoteException;

import model.PlayerInterface;
import toolkit.Debug;
import data.GameInterface;
import data.SessionInterface;
import exception.GameException;
import gui.OptionPane;

public class Table extends Controller
{
	private GameInterface gameData;
	
	private int gameId;
	
	private view.Table view;
	
	public Table(GameInterface gameData)
	{
		this.gameData = gameData;
		
		this.gameId = gameData.getId();
		
		view = new view.Table(this, gameData);
		setView(view);
	}
	
	public void dispatch()
	{
		view.getFrame().setTitle(gameData.toString());
		
		watchGame();
	}

	public view.Table getView()
	{
		return view;
	}
	
	public void watchGame()
	{
		client.watchGame(gameId, this);
		
		try
		{
			SessionInterface session = serverRemote.watchGame(gameId, user);
			
			view.updateSession(session);
		}
		catch (RemoteException e)
		{
			Debug.log(e);
		}
	}

	public void leaveGame()
	{
		client.leaveGame(gameId);
		
		try
		{
			serverRemote.leaveGame(gameId, user);
		}
		catch (RemoteException e)
		{
			Debug.log(e);
		}
	}
	
	public void join(int seatIndex)
	{
		if (user instanceof PlayerInterface)
		{
			PlayerInterface player = (PlayerInterface) user;
			
			try
			{
				serverRemote.joinGame(gameId, player, seatIndex);
				
				view.enableStatistics();
			}
			catch (GameException e)
			{
				OptionPane.showError("Game error", e.getMessage());
			}
			catch (RemoteException e)
			{
				Debug.log(e);
				
				OptionPane.showError("Error", "something went wrong when trying to join.");
			}
		}
	}
	
	public void statistics()
	{
		forward(new controller.Statistics(gameId), true);
	}
	
	public void sendChatMessage(String message)
	{
		try
		{
			serverRemote.sendChatMessage(gameId, user, message);
		}
		catch (RemoteException e)
		{
			Debug.log(e);
		}
	}
}
